import React, { useState, useEffect } from 'react';
import Image from 'next/image';
import { useAuth } from '../contexts/AuthContext';
import axios from 'axios';

interface PaymentModalProps {
  onClose: () => void;
  onPaymentSuccess: () => void;
  onTokenExpired: () => void;
  photoResult: {
    originalPreview: string;
    originalLayout: string;
  } | null;
}

const PaymentModal: React.FC<PaymentModalProps> = ({ onClose, onPaymentSuccess, onTokenExpired, photoResult }) => {
  const { user, checkDownloadPermission } = useAuth();
  const [timeLeft, setTimeLeft] = useState(300000); // 5 minutes in milliseconds
  const [error, setError] = useState<string | null>(null);
  const [showDownloadComplete, setShowDownloadComplete] = useState(false);
  const [closeCountdown, setCloseCountdown] = useState(5); // 5 seconds countdown

  useEffect(() => {
    const timer = setInterval(() => {
      setTimeLeft((prevTime) => {
        if (prevTime <= 0) {
          clearInterval(timer);
          onClose();
          return 0;
        }
        return prevTime - 10;
      });
    }, 10);

    const checkPermissionInterval = setInterval(async () => {
      try {
        const hasPermission = await checkDownloadPermission();
        if (hasPermission) {
          clearInterval(checkPermissionInterval);
          if (photoResult) {
            await handleDownload(photoResult.originalPreview, 'preview.jpg');
            await handleDownload(photoResult.originalLayout, 'layout.jpg');
            setShowDownloadComplete(true);
            
            // Start the countdown
            const countdownTimer = setInterval(() => {
              setCloseCountdown((prevCount) => {
                if (prevCount <= 1) {
                  clearInterval(countdownTimer);
                  setShowDownloadComplete(false);
                  onClose();
                  return 0;
                }
                return prevCount - 1;
              });
            }, 1000);
          }
          onPaymentSuccess();
        }
      } catch (error) {
        console.error('检查下载权限失败:', error);
        if (axios.isAxiosError(error) && error.response?.status === 401) {
          clearInterval(checkPermissionInterval);
          onTokenExpired();
          onClose();
        } else {
          setError(`检查下载权限失败: ${error instanceof Error ? error.message : '未知错误'}`);
        }
      }
    }, 2000);

    return () => {
      clearInterval(timer);
      clearInterval(checkPermissionInterval);
    };
  }, [onClose, onPaymentSuccess, photoResult, onTokenExpired, checkDownloadPermission]);

  const formatTime = (ms: number) => {
    const minutes = Math.floor(ms / 60000);
    const seconds = Math.floor((ms % 60000) / 1000);
    const milliseconds = ms % 1000;
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}.${milliseconds.toString().padStart(3, '0')}`;
  };

  const handleDownload = async (dataUrl: string, fileName: string) => {
    return new Promise<void>((resolve) => {
      const link = document.createElement('a');
      link.href = dataUrl;
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      setTimeout(resolve, 100); // 给浏览器一些时间来初始化下载
    });
  };

  const handleCloseDownloadComplete = () => {
    setShowDownloadComplete(false);
    onClose();
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 backdrop-blur-sm flex items-center justify-center">
      <div className="bg-white rounded-2xl shadow-xl p-8 w-96 max-w-full mx-4 relative">
        {!showDownloadComplete ? (
          <>
            <button
              onClick={onClose}
              className="absolute top-4 right-4 text-gray-400 hover:text-gray-600 transition-colors"
              aria-label="关闭"
            >
              <svg className="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>

            <h2 className="text-2xl font-bold text-center mb-6 text-gray-800">微信支付</h2>

            <div className="flex justify-center mb-6">
              <div className="relative w-48 h-48 bg-gray-100 rounded-lg overflow-hidden">
                <Image src="/wepay.jpg" alt="WeChat Pay QR Code" layout="fill" objectFit="cover" />
              </div>
            </div>

            <p className="text-center text-gray-600 mb-4">
              请使用微信扫描上方二维码进行支付
            </p>

            <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
              <p className="text-sm text-blue-800 font-medium">
                重要提示：支付时请备注邮箱 <strong>{user?.email}</strong>
              </p>
            </div>

            <div className="text-center mb-6">
              <p className="text-sm text-gray-500 mb-1">支付倒计时</p>
              <p className="text-2xl font-bold text-blue-600">{formatTime(timeLeft)}</p>
            </div>

            {error && (
              <p className="text-red-500 text-sm mt-4">{error}</p>
            )}

            <p className="text-center text-sm text-gray-500 mb-4">
              支付成功后将自动下载图片
            </p>
          </>
        ) : (
          <div className="text-center">
            <h2 className="text-2xl font-bold mb-4 text-green-600">下载完成</h2>
            <p className="mb-6">您的图片已成功下载。此窗口将在 {closeCountdown} 秒后自动关闭。</p>
            <button
              onClick={handleCloseDownloadComplete}
              className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 transition-colors"
            >
              关闭
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default PaymentModal;